package com.shigu.itemCate.service;

import com.alibaba.fastjson.JSON;
import com.opentae.data.mall.beans.MallItem;
import com.opentae.data.mall.beans.MallItemcats;
import com.opentae.data.mall.examples.MallItemExample;
import com.opentae.data.mall.examples.MallItemcatsExample;
import com.opentae.data.mall.interfaces.MallItemMapper;
import com.opentae.data.mall.interfaces.MallItemcatsMapper;
import com.opentae.data.mall.interfaces.UserInviteInfoMapper;
import com.shigu.ListDto;
import com.shigu.PageResponse;
import com.shigu.account.api.VipManagerService;
import com.shigu.constant.service.SystemConstantService;
import com.shigu.exceptions.WapException;
import com.shigu.item.enums.ImgRule;
import com.shigu.itemCate.api.ItemCateService;
import com.shigu.itemCate.bo.CateBo;
import com.shigu.itemCate.bo.ModCateBo;
import com.shigu.itemCate.vo.CateVo;
import com.shigu.itemCate.vo.ChildCateVo;
import com.shigu.item.vo.GoodsListVo;
import com.shigu.itemCate.vo.MainCateVo;
import com.shigu.searchWord.api.SearchWordService;
import com.shigu.user.utils.RedisIO;
import com.shigu.util.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/*
 * create by  过儿  2019-06-04
 *
 */
@Service(value = "itemCateServiceImpl")
public class ItemCateServiceImpl implements ItemCateService {

    private static String initCid = "-1";//根目录的id 为 -1

    private static final Logger logger = LoggerFactory.getLogger(ItemCateServiceImpl.class);

    @Autowired
    MallItemcatsMapper mallItemcatsMapper;

    @Autowired
    MallItemMapper mallItemMapper;

    @Autowired
    SystemConstantService systemConstantService;
    @Autowired
    UserInviteInfoMapper userInviteInfoMapper;

    @Resource(name = "vipManagerServiceImpl")
    VipManagerService vipManagerService;

    @Resource(name = "searchWordServiceImpl")
    SearchWordService searchWordService;

    @Autowired
    RedisIO redisIO;

    @Override
    public void addCate(CateBo bo) throws WapException {
        MallItemcatsExample example = new MallItemcatsExample();

        example.createCriteria().andCatNameEqualTo(bo.getCateName()).andParentCidEqualTo(bo.getParentCid());

        int num = mallItemcatsMapper.countByExample(example);

        if (num > 0) {
            throw new WapException("此目录下已存在该类目名");
        }

        MallItemcats cate = new MallItemcats();
        cate.setCatName(bo.getCateName());
        cate.setParentCid(bo.getParentCid());
        cate.setCreateTime(new Date());
        cate.setImgUrl(bo.getImgUrl());
        cate.setSortOrder(bo.getSortOrder());
        mallItemcatsMapper.insertSelective(cate);
    }

    @Override
    public void delCate(Long cid) throws WapException {
        int childCate = mallItemcatsMapper.countChild(cid);
        if (childCate > 0) {
            throw new WapException("该目录下还有子目录");
        }
        int childItem = mallItemMapper.countChildItem(cid);
        if (childItem > 0) {
            throw new WapException("该目录下还有商品");
        }

        mallItemcatsMapper.deleteByPrimaryKey(cid);

    }

    @Override
    public void modifyCate(ModCateBo bo) {
        MallItemcats cate = new MallItemcats();
        cate.setCid(bo.getCid());
        cate.setImgUrl(bo.getImgUrl());
        cate.setCatName(bo.getCateName());
        cate.setSortOrder(bo.getSortOrder());
        mallItemcatsMapper.updateByPrimaryKeySelective(cate);
    }

    @Override
    public List<MallItemcats> selItemCate(String parentCid) {
        if (StringUtils.isBlank(parentCid) || "null".equals(parentCid) || "undefined".equals(parentCid)) {
            parentCid = initCid;
        }
        Long cid = Long.parseLong(parentCid);

        MallItemcatsExample example = new MallItemcatsExample();
        example.createCriteria().andParentCidEqualTo(cid);
        example.setOrderByClause("sort_order desc");

        return mallItemcatsMapper.selectByExample(example);
    }

    @Override
    public ListDto<MallItem> selCateItems(Integer page, Integer size, String sort, String cid, String keyword) {
        //todo 排序sort的判断
        MallItemExample example = new MallItemExample();
        example.setOrderByClause("create_time desc");
        example.setStartIndex((page - 1) * size);
        example.setEndIndex(size);
        MallItemExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(cid)) {
            criteria.andCidEqualTo(Long.parseLong(cid));
        }
        if (StringUtils.isNotBlank(keyword)) {
            criteria.andTitleLike("%" + keyword + "%");
        }

        int total = mallItemMapper.countByExample(example);
        List<MallItem> list = mallItemMapper.selectByConditionList(example);

        return new ListDto<>(total > page * size, total, list);
    }

    @Override
    public PageResponse<CateVo> selCate(String parentCid) {
        List<MallItemcats> list = selItemCate(parentCid);

        PageResponse<CateVo> response = new PageResponse<>();
        response.setData(list.stream().map(o -> {
            CateVo vo = new CateVo();
            vo.setCid(o.getCid());
            vo.setCateName(o.getCatName());
            vo.setImgUrl(o.getImgUrl());
            vo.setWeight(o.getSortOrder());
            vo.setLabel(o.getCatName());
            vo.setParentCid(o.getParentCid());
            vo.setLevel(2);//前端规定 2为父节点
            List<MallItemcats> child = selItemCate(o.getCid() + "");
            vo.setChildren(child.stream().map(c -> {
                CateVo cvo = new CateVo();
                cvo.setCid(c.getCid());
                cvo.setCateName(c.getCatName());
                cvo.setImgUrl(c.getImgUrl());
                cvo.setWeight(c.getSortOrder());
                cvo.setLabel(c.getCatName());
                cvo.setLevel(1);//规定 1 为child
                cvo.setParentCid(c.getParentCid());
                return cvo;
            }).collect(Collectors.toList()));
            return vo;
        }).collect(Collectors.toList()));
        return response;
    }

    @Override
    public PageResponse<MainCateVo> getMainCateList() {
        List<MallItemcats> cate = selItemCate("");

        PageResponse<MainCateVo> response = new PageResponse<>();
        response.setData(cate.stream().map(o -> {
            MainCateVo vo = new MainCateVo();
            vo.setCateId(o.getCid());
            vo.setCateName(o.getCatName());
            return vo;
        }).collect(Collectors.toList()));
        return response.success();
    }

    @Override
    public PageResponse<ChildCateVo> getChildCateList(String mainCateId) {
        PageResponse<ChildCateVo> response = new PageResponse<>();
        if (StringUtils.isNotBlank(mainCateId)) {
            List<MallItemcats> cate = selItemCate(mainCateId);
            response.setData(cate.stream().map(o -> {
                ChildCateVo vo = new ChildCateVo();
                vo.setChildCateId(o.getCid());
                vo.setChildCateName(o.getCatName());
                vo.setImgUrl(o.getImgUrl() + ImgRule.rule3.getText());
                return vo;
            }).collect(Collectors.toList()));
        }
        return response.success();
    }

    @Override
    public PageResponse<GoodsListVo> getGoodsList(Integer page, Integer size, Long mallUserId, String sort, String childCateId, String keyword) {
        //保存搜索记录
        searchWordService.insertWord(keyword, mallUserId);
        //查询用户费率
        Double rate = vipManagerService.userRate(mallUserId, "");

        //key值使用  rate,page,sort,childCateId,keyword 拼接
        String keystr[] = {"goodsList", rate.toString(), page.toString(), sort, childCateId, keyword};
        String key = StringUtils.join(keystr, "_");
        PageResponse<GoodsListVo> response = redisIO.get(key, PageResponse.class);
        if (response != null) {
//            logger.error("response:" + JSON.toJSONString(response));
            return response;
        }
        response = new PageResponse<>();

        ListDto<MallItem> dto = selCateItems(page, size, sort, childCateId, keyword);
        response.setTotal(dto.getTotal());
        response.setHasNext(dto.getHasNext());
        List<GoodsListVo> data = new ArrayList<>();

        //lambda 表达式要求rate 为final 所以 使用for 循环转换
        for (int i = 0; i < dto.getData().size(); i++) {
            MallItem item = dto.getData().get(i);
            GoodsListVo vo = new GoodsListVo();
            String[] imgs = item.getImages().split(",");
            vo.setImgSrc(imgs[0] + ImgRule.rule1.getText());
            vo.setItemId(item.getItemId());
            vo.setPrice(MoneyUtil.formatPriceMoney(item.getDiscount()));
            vo.setTitle(item.getTitle());
            //设置佣金
            vo.setCommission(MoneyUtil.formatPriceMoney(item.getDiscount() * rate));
            data.add(vo);
        }
        response.setData(data);
        //放入缓存中,30s
        redisIO.putTemp(key, response, 30);

        return response.success();
    }
}
